package echo.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.TimeUnit;

/**
 * @author： zhangnan
 * @date： 2025/4/14 19:09
 * @description： TODO
 * @modifiedBy：
 * @version: 1.0
 */
public class BlockingHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws InterruptedException {
        // 打印当前处理消息的线程名称和处理次数
        System.out.println("Processing message on thread: " + Thread.currentThread().getName() + " msg: " + msg);
        try {
            TimeUnit.SECONDS.sleep(30);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String response = "Processed: " + msg;
        // 将响应消息写回客户端并刷新缓冲区
        ctx.writeAndFlush(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 打印异常堆栈信息
        cause.printStackTrace();
        // 关闭客户端的连接
        ctx.close();
    }


}
